package com.hooper.api.gateway.filter;

import com.hooper.api.common.model.InterfaceInfoDto;
import com.hooper.api.common.model.UserInfo;
import com.hooper.api.common.service.*;
import com.hooper.api.common.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.*;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 校验 用户/开发者 是否有权限调用接口
 */
@Slf4j
@Component
public class InterfaceGlobalFilter implements GlobalFilter, Ordered {

    @DubboReference
    private UserInterfaceInfoService4Dubbo userInterfaceInfoService4Dubbo;

    @DubboReference
    private UserService4Dubbo userService4Dubbo;
    @DubboReference
    private InterfaceInfoService4Dubbo interfaceInfoService4Dubbo;

    private static final int STATUS_BANNED = 0;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        String method = request.getMethodValue();
        log.info("请求唯一标识：" + request.getId());
        log.info("请求路径：" + path);
        log.info("请求方法：" + method);
        log.info("请求参数：" + request.getQueryParams());
        String sourceAddress = request.getLocalAddress().getHostString();
        log.info("请求来源地址：" + sourceAddress);
        log.info("请求来源地址：" + request.getRemoteAddress());
        ServerHttpResponse response = exchange.getResponse();

        //鉴权 判断用户的ak sk是否正确
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String sign = headers.getFirst("sign");
        String timestamp = headers.getFirst("timestamp");
        log.info("timestamp: " + timestamp);
        String nonce = headers.getFirst("nonce");
        //非空校验
        if (ObjectUtils.anyNull(accessKey, sign, timestamp, nonce)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //校验时间戳
        final long FIVE_MINUTES = 5 * 60 * 1000;
        if (Long.parseLong(timestamp) < (System.currentTimeMillis() / 1000) - FIVE_MINUTES) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //校验随机数
        if (Integer.parseInt(nonce) % 3 != 0) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //rpc调用 查询该用户的ak sk 是否正确
        UserInfo userInfo = userService4Dubbo.getUserInfoByAccessKey(accessKey);
        if (userInfo == null) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        String secretKey = userInfo.getSecretKey();
        //校验签名
        String realSign = SignUtil.sign(secretKey,timestamp);
        if (!realSign.equals(sign)) {
            log.info("realSign: " + realSign);
            log.info("sign: " + sign);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //rpc调用 查询该用户是否有权限调用该接口
        InterfaceInfoDto interfaceInfo = interfaceInfoService4Dubbo
                .getInterfaceInfoByUrlAndMethod(path, method);
        if (interfaceInfo == null || interfaceInfo.getStatus().equals(STATUS_BANNED)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //处理响应，在接口正确响应后，接口调用信息+1
        return handleResponse(exchange, chain, interfaceInfo.getId(), userInfo.getId());
    }

    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain, long interfaceInfoId, long userId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 缓存数据的工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 拿到响应码
            HttpStatus statusCode = originalResponse.getStatusCode();
            if (statusCode == HttpStatus.OK) {
                // 装饰，增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                    // 等调用完转发的接口后才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 往返回值里写数据
                            // 拼接字符串
                            return super.writeWith(
                                    fluxBody.map(dataBuffer -> {
                                        // 7. 调用成功，接口调用次数 + 1 invokeCount
                                        try {
                                            userInterfaceInfoService4Dubbo.invokeCount(interfaceInfoId, userId);
                                        } catch (Exception e) {
                                            log.error("invokeCount error", e);
                                        }
                                        byte[] content = new byte[dataBuffer.readableByteCount()];
                                        dataBuffer.read(content);
                                        DataBufferUtils.release(dataBuffer);//释放掉内存
                                        // 构建日志
                                        StringBuilder sb2 = new StringBuilder(200);
                                        List<Object> rspArgs = new ArrayList<>();
                                        rspArgs.add(originalResponse.getStatusCode());
                                        String data = new String(content, StandardCharsets.UTF_8); //data
                                        sb2.append(data);
                                        // 打印日志
                                        log.info("响应结果：" + data);
                                        return bufferFactory.wrap(content);
                                    }));
                        } else {
                            // 8. 调用失败，返回一个规范的错误码
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 设置 response 对象为装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange); // 降级处理返回数据
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }


    @Override
    public int getOrder() {
        //内部过滤器的执行顺序为从0开始
        //因此，我们的过滤器应该在内部过滤器之前执行
        return 0;
    }
}